package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomExcepion;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;//购物车

    @Autowired
    private AddressBookService addressBookService;//地址簿

    @Autowired
    private UserService userService;//用户

    @Autowired
    private OrderDetailService orderDetailService;//

    @Override
    public void submit(Orders orders) {
        //查询当前登录用户
        Long currentUserId = BaseContext.getCurrentId();
        //0.1查询购物车数据
        LambdaQueryWrapper<ShoppingCart>spLqw = new LambdaQueryWrapper<>();
        spLqw.eq(ShoppingCart::getUserId,currentUserId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(spLqw);
        if (shoppingCartList==null||shoppingCartList.size()<=0) {
            throw new CustomExcepion("购物车列表为空!");
        }
        //0.2根据地址簿id查询地址薄信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        //0.3根据当前登录用户id，查询用户信息
        User user = userService.getById(currentUserId);
        long orderId = IdWorker.getId();//利用mybatisplus生成订单id
        //0.4准备订单明细封装（把购物车的数据封装到订单明细）
        AtomicInteger amount = new AtomicInteger(0);
        List<OrderDetail>orderDetailList =new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            //封装订单明细（从购物车中复制数据）
            OrderDetail orderDetail =new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(orderId);
            orderDetailList.add(orderDetail);
            //计算总金额
            BigDecimal cartAmount = shoppingCart.getAmount();//单价
            Integer number = shoppingCart.getNumber();//数量
            BigDecimal multiply = cartAmount.multiply(new BigDecimal(number));//小计
            amount.addAndGet(multiply.intValue());//将小计追加到 总金额中
        }
        //0.5准备订单对象
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.intValue()));//总金额
        orders.setUserId(currentUserId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //1.保存订单信息
        save(orders);
        //2.保存订单明细
        orderDetailService.saveBatch(orderDetailList);
        //3.清除购物车
        shoppingCartService.remove(spLqw);
    }

    /**
     * 再来一单
     * @param order
     */
    @Override
    public void again(Orders order) {
        Orders orders = getById(order.getId());

        LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderDetail::getOrderId,order.getId());
        List<OrderDetail> list = orderDetailService.list(lqw);

        long orderId = IdWorker.getId();
        orders.setId(orderId);
        orders.setStatus(2);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        save(orders);

        List<OrderDetail> collect = list.stream().map(item -> {
            item.setOrderId(orderId);
            item.setId(null);
            return item;
        }).collect(Collectors.toList());
        orderDetailService.saveBatch(collect);
    }
}